<template>
    <el-dropdown placement="bottom" max-height="300" trigger="hover" :hide-on-click="false">
        <el-button type="info">
            <Icon name="el-Grid"></Icon>
            <span>列设置</span>
        </el-button>
        <template #dropdown>
            <el-dropdown-menu v-if="showColumnSetArr.length !== 0">
                <el-dropdown-item>
                    <el-checkbox
                        v-model="checkAll"
                        :indeterminate="isIndeterminate"
                        :label="checkAll ? '全不选' : '全选'"
                        @change="onShowColumnCheckAllChange"
                    />
                </el-dropdown-item>
                <el-dropdown-item v-for="(item, index) in showColumnSetArr" :key="index">
                    <el-checkbox :model-value="item.show" :label="item.label" @change="onShowColumnCheckChange($event, item.label)" />
                </el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>
</template>

<script setup lang="ts">
interface Props {
    columns?: TableColumnType<any>[]
}
interface showColumnSet {
    label: string
    show: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(['onShowColumnChange'])
// 是否选择所有
const checkAll = ref(false)
// 选择所有checkBox的状态是否确定
const isIndeterminate = ref(true)
// 所有列数组
const columnArr = ref(props.columns)
// 过滤出能切换显示列的数组
const showColumnSetArr = computed(() => {
    let showCount = 0
    const arr: showColumnSet[] = []
    props.columns?.forEach((item) => {
        if (item.type !== 'selection' && item.type !== 'actions') {
            arr.push({ label: item.label ?? '', show: item.show ?? true })
            if (item.show !== false) {
                showCount = showCount + 1
            }
        }
    })
    checkAll.value = showCount === arr.length
    isIndeterminate.value = showCount > 0 && showCount < arr.length
    return arr
})
// 显示或者隐藏所有列
const onShowColumnCheckAllChange = () => {
    columnArr.value?.forEach((item) => {
        if (item.type !== 'selection' && item.type !== 'actions') {
            item.show = checkAll.value
        }
    })
    isIndeterminate.value = false
    emit('onShowColumnChange', columnArr.value)
}
// 显示或者隐藏列
const onShowColumnCheckChange = (value: any, label: string) => {
    let showCount = 0
    columnArr.value?.forEach((item) => {
        if (item.type !== 'selection' && item.type !== 'actions') {
            if (item.label === label) {
                item.show = value as boolean
            }
            if (item.show !== false) {
                showCount = showCount + 1
            }
        }
    })
    checkAll.value = showCount === showColumnSetArr.value.length
    isIndeterminate.value = showCount > 0 && showCount < showColumnSetArr.value.length
    emit('onShowColumnChange', columnArr.value)
}
</script>

<style lang="scss" scoped></style>
